package com.jzr.board.ui.voip

import android.os.SystemClock
import android.view.View
import android.view.WindowManager
import com.blankj.utilcode.utils.LogUtils
import com.blankj.utilcode.utils.ToastUtils
import com.jzr.board.R
import com.jzr.board.base.BaseActivity
import com.jzr.board.base.Constant
import com.jzr.board.utils.rtc.AEvent
import com.jzr.board.utils.rtc.IEventListener
import com.starrtc.starrtcsdk.api.XHClient
import com.starrtc.starrtcsdk.api.XHConstants
import com.starrtc.starrtcsdk.api.XHSDKHelper
import com.starrtc.starrtcsdk.api.XHVoipManager
import com.starrtc.starrtcsdk.apiInterface.IXHResultCallback
import com.starrtc.starrtcsdk.core.audio.StarRTCAudioManager
import com.starrtc.starrtcsdk.core.pusher.XHCameraRecorder
import kotlinx.android.synthetic.main.activity_voip.*

class VoipActivity : BaseActivity(), IEventListener, View.OnClickListener {


    private var starRTCAudioManager: StarRTCAudioManager? = null

    private var voipManager: XHVoipManager? = null

    private var xhsdkHelper: XHSDKHelper? = null

    companion object{
        var ACTION = "ACTION"
        var RING = "RING"
        var CALLING = "CALLING"
    }


    private var action: String? = null
    private var targetId: String? = null
    private var isTalking = false

    override fun getLayoutId(): Int {
        return R.layout.activity_voip
    }

    override fun attachView() {

    }

    override fun detachView() {

    }

    override fun initView() {

        calling_hangup.setOnClickListener(this)
        talking_hangup.setOnClickListener(this)
        speaker_on_btn.setOnClickListener(this)
        speaker_off_btn.setOnClickListener(this)
        switch_camera.setOnClickListener(this)

        starRTCAudioManager = StarRTCAudioManager.create(this.applicationContext)
        starRTCAudioManager?.start { selectedAudioDevice, availableAudioDevices ->
            LogUtils.e("onAudioDeviceChanged ", selectedAudioDevice.name)
        }

        starRTCAudioManager?.setDefaultAudioDevice(StarRTCAudioManager.AudioDevice.SPEAKER_PHONE)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )

        voipManager = XHClient.getInstance().voipManager
        voipManager?.setRecorder(XHCameraRecorder())
        voipManager?.rtcMediaType =
            XHConstants.XHRtcMediaTypeEnum.STAR_RTC_MEDIA_TYPE_VIDEO_AND_AUDIO

        addListener()

        targetId = intent.getStringExtra("targetId")
        action = intent.getStringExtra(ACTION)

        selfPlayer?.setZOrderMediaOverlay(true)
        targetPlayer?.setOnClickListener {
            if (isTalking) {
                findViewById(R.id.talking_view).visibility =
                    if (findViewById(R.id.talking_view).visibility == View.VISIBLE) View.INVISIBLE else View.VISIBLE
            }
        }

        if (action == CALLING) {
            showCallingView()
            xhsdkHelper = XHSDKHelper()
            xhsdkHelper?.setDefaultCameraId(1)
            xhsdkHelper?.startPerview(this, targetPlayer)
            voipManager?.call(this, targetId,
                object : IXHResultCallback {
                    override fun success(data: Any) {
                        xhsdkHelper?.stopPerview()
                        xhsdkHelper = null
                    }

                    override fun failed(errMsg: String) {
                        stopAndFinish()
                    }
                })
        } else {
            onPickup()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        removeListener()
    }

    private fun onPickup() {
        voipManager?.accept(
            this,
            targetId,
            object : IXHResultCallback {
                override fun success(data: Any?) {
                    LogUtils.e("newVoip", "onPickup OK! RecSessionId:$data")
                }

                override fun failed(errMsg: String?) {
                    LogUtils.e("newVoip", "onPickup failed ")
                    stopAndFinish()
                }
            })
        showTalkingView()
    }

    private fun setupViews() {
        voipManager?.setupView(
            selfPlayer,
            targetPlayer,
            callback
        )
    }

    private var callback: IXHResultCallback? = object : IXHResultCallback {
        override fun success(data: Any?) {
            LogUtils.e("newVoip", "setupView success")
        }

        override fun failed(errMsg: String?) {
            LogUtils.e("newVoip", "setupView failed")
            stopAndFinish()
        }
    }

    private fun stopAndFinish() {
        if (starRTCAudioManager != null) {
            starRTCAudioManager?.stop()
        }
        finish()
    }

    private fun showCallingView() {
        calling_view.visibility = View.VISIBLE
        talking_view.visibility = View.GONE
    }

    private fun showTalkingView() {
        isTalking = true
        calling_view.visibility = View.GONE
        talking_view.visibility = View.VISIBLE
        timer.base = SystemClock.elapsedRealtime()
        timer.start()
        setupViews()
    }

    override fun dispatchEvent(
        aEventID: String?,
        success: Boolean,
        eventObj: Any
    ) {
//        super.dispatchEvent(aEventID, success, eventObj)
        when (aEventID) {
            AEvent.AEVENT_VOIP_REV_BUSY -> {
                LogUtils.e("", "对方线路忙")
                ToastUtils.showShortToast("对方线路忙")
                if (xhsdkHelper != null) {
                    xhsdkHelper?.stopPerview()
                    xhsdkHelper = null
                }
                stopAndFinish()
            }
            AEvent.AEVENT_VOIP_REV_REFUSED -> {
                LogUtils.e("", "对方拒绝通话")
                ToastUtils.showShortToast("对方拒绝通话")
                if (xhsdkHelper != null) {
                    xhsdkHelper?.stopPerview()
                    xhsdkHelper = null
                }
                stopAndFinish()
            }
            AEvent.AEVENT_VOIP_REV_HANGUP -> {
                LogUtils.e("", "对方已挂断")
                ToastUtils.showShortToast("对方已挂断")
                timer.stop()
                stopAndFinish()
            }
            AEvent.AEVENT_VOIP_REV_CONNECT -> {
                LogUtils.e("", "对方允许通话")
                showTalkingView()
            }
            AEvent.AEVENT_VOIP_REV_ERROR -> {
                LogUtils.e("", eventObj as String)
                if (xhsdkHelper != null) {
                    xhsdkHelper?.stopPerview()
                    xhsdkHelper = null
                }
                stopAndFinish()
            }
            AEvent.AEVENT_VOIP_TRANS_STATE_CHANGED -> findViewById(R.id.state).setBackgroundColor(if (eventObj as Int == 0) -0x100 else -0xd66bff)
        }
    }

    private fun addListener() {
        AEvent.addListener(AEvent.AEVENT_VOIP_INIT_COMPLETE, this)
        AEvent.addListener(AEvent.AEVENT_VOIP_REV_BUSY, this)
        AEvent.addListener(AEvent.AEVENT_VOIP_REV_REFUSED, this)
        AEvent.addListener(AEvent.AEVENT_VOIP_REV_HANGUP, this)
        AEvent.addListener(AEvent.AEVENT_VOIP_REV_CONNECT, this)
        AEvent.addListener(AEvent.AEVENT_VOIP_REV_ERROR, this)
        AEvent.addListener(AEvent.AEVENT_VOIP_TRANS_STATE_CHANGED, this)
    }

    fun removeListener() {
        Constant.canPickupVoip = true
        AEvent.removeListener(AEvent.AEVENT_VOIP_INIT_COMPLETE, this)
        AEvent.removeListener(AEvent.AEVENT_VOIP_REV_BUSY, this)
        AEvent.removeListener(AEvent.AEVENT_VOIP_REV_REFUSED, this)
        AEvent.removeListener(AEvent.AEVENT_VOIP_REV_HANGUP, this)
        AEvent.removeListener(AEvent.AEVENT_VOIP_REV_CONNECT, this)
        AEvent.removeListener(AEvent.AEVENT_VOIP_REV_ERROR, this)
        AEvent.removeListener(AEvent.AEVENT_VOIP_TRANS_STATE_CHANGED, this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.calling_hangup -> {
                voipManager?.cancel(object : IXHResultCallback {
                    override fun success(data: Any?) {
                        stopAndFinish()
                    }

                    override fun failed(errMsg: String?) {
                        stopAndFinish()
                    }
                })

                if (xhsdkHelper != null) {
                    xhsdkHelper?.stopPerview()
                    xhsdkHelper = null
                }
            }
            R.id.talking_hangup -> {
                voipManager?.hangup(object : IXHResultCallback {
                    override fun success(data: Any?) {
                        stopAndFinish()
                    }

                    override fun failed(errMsg: String?) {
                        stopAndFinish()
                    }
                })
            }

            R.id.speaker_on_btn -> {
                starRTCAudioManager?.setSpeakerphoneOn(true)
                speaker_on_btn.isSelected = true
                speaker_off_btn.isSelected = false
            }

            R.id.speaker_off_btn -> {
                starRTCAudioManager?.setSpeakerphoneOn(false)
                speaker_on_btn.isSelected = false
                speaker_off_btn.isSelected = true
            }
            R.id.switch_camera->{
                voipManager?.switchCamera()
            }

        }
    }

}
